<?php

namespace App\Admin\Controllers;

use Encore\Admin\Form;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Tree;
use Encore\Admin\Widgets\Box;
use App\Models\Menu;
use Encore\Admin\Controllers\MenuController as BaseMenuController;

class MenuController extends BaseMenuController
{

    protected $backend='';

	/**
     * Index interface.
     *
     * @param Content $content
     *
     * @return Content
     */
    public function index(Content $content)
    {

		$backend = request('backend','admin');
		$this->backend = $backend;
		$sel='';
		foreach(get_backends() as $k=>$nav){
			if($backend == $k){
				$sel .= '<li class="active"><a href="'.admin_base_path('auth/menu').'?backend='.$k.'">'.$nav.'</a></li>';
			}else{
				$sel .= '<li><a href="'.admin_base_path('auth/menu').'?backend='.$k.'">'.$nav.'</a></li>';
			}
		}
		$navbar = 	'<nav class="navbar navbar-default">
					  <div class="container-fluid">
						<div class="navbar-header">
						  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
							<span class="sr-only">Toggle navigation</span>
							<span class="icon-bar"></span>
							<span class="icon-bar"></span>
							<span class="icon-bar"></span>
						  </button>
						  <span class="navbar-brand">后台：</span>
						</div>
						<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
						  <ul class="nav navbar-nav">'.$sel.'
						  </ul>
						</div>
					  </div>
					</nav>';
		return $content
            ->title(trans('admin.menu'))
            ->description(trans('admin.list'))
            ->row(function (Row $row) use($navbar,$backend){
				$row->column(12, $navbar);
                $row->column(6, $this->treeView()->render());

                $row->column(6, function (Column $column) use($backend){
                    $form = new \Encore\Admin\Widgets\Form();
                    $form->action(admin_base_path('auth/menu?backend='.$backend));

                    $permissionModel = config('admin.database.permissions_model');
                    $roleModel = config('admin.database.roles_model');
                    $form->select('parent_id', trans('admin.parent_id'))->options(Menu::selectOptions());
                    /*
                    $form->select('parent_id', trans('admin.parent_id'))->options(Menu::selectOptions(function ($query) use($backend){
                        return $query->where('backend', $backend);
                    }));*/
                    $form->text('title', trans('admin.title'))->rules('required');
                    $form->icon('icon', trans('admin.icon'))->default('fa-bars')->rules('required')->help($this->iconHelp());
                    $form->text('uri', trans('admin.uri'));
                    $form->multipleSelect('roles', '角色限止')->options($roleModel::pluck('name', 'id'));
                    if ((new Menu())->withPermission()) {
                        $form->select('permission', '权限限止')->options($permissionModel::pluck('name', 'slug'));
                    }
					$form->hidden('backend')->default($backend);
                    $form->hidden('_token')->default(csrf_token());

                    $column->append((new Box(trans('admin.new'), $form))->style('success'));
                });
            });
    }

    /**
     * Redirect to edit page.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function show($id)
    {
        return redirect()->route('admin.auth.menu.edit', ['id' => $id]);
    }


   /**
     * @return \Encore\Admin\Tree
     */
    protected function treeView()
    {
        $backend=$this->backend;
        $menuModel = new Menu($this->backend);
		//dump($menuModel->get()->toArray());
        /*$menuModel = $menuModel->withQuery(function($query) use($backend){
            return $query->where('backend', $backend);
        });*/
        return $menuModel::tree(function (Tree $tree) {
            $tree->disableCreate();
            $tree->branch(function ($branch) {
                $payload = "<i class='fa {$branch['icon']}'></i>&nbsp;<strong>{$branch['title']}</strong>";

                if (!isset($branch['children'])) {
                    if (url()->isValidUrl($branch['uri'])) {
                        $uri = $branch['uri'];
                    } else {
                        $uri = '/'.$branch['backend'].str_start($branch['uri'],'/');
                    }

                    $payload .= "&nbsp;&nbsp;&nbsp;<a href=\"$uri\" class=\"dd-nodrag\">$uri</a>";
                }

                return $payload;
            });
        });
    }

    /**
     * Edit interface.
     *
     * @param string  $id
     * @param Content $content
     *
     * @return Content
     */
    public function edit($id, Content $content)
    {
        $rs = Menu::findOrFail($id);
		$this->backend = $rs['backend'];
		return $content
            ->title(trans('admin.menu'))
            ->description(trans('admin.edit'))
            ->row($this->form()->edit($id));
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    public function form()
    {
        $permissionModel = config('admin.database.permissions_model');
        $roleModel = config('admin.database.roles_model');
        $backend = $this->backend;
        $menuModel = new Menu($backend);
        $form = new Form($menuModel);
        $form->display('id', 'ID');
        $form->display('backend', '后台');
        $form->select('parent_id', trans('admin.parent_id'))->options(Menu::selectOptions());
        $form->text('title', trans('admin.title'))->rules('required');
        $form->icon('icon', trans('admin.icon'))->default('fa-bars')->rules('required')->help($this->iconHelp());
        $form->text('uri', trans('admin.uri'));
        $form->multipleSelect('roles', '角色限止')->options($roleModel::pluck('name', 'id'));
        if ($form->model()->withPermission()) {
            $form->select('permission', '权限限止')->options($permissionModel::pluck('name', 'slug'));
        }
/*
        $form->saved(function (Form $form) {
            //return back()->with(compact('success'));
        });*/
        return $form;
    }
}
